
var express = require('express');
var router = express.Router();
var db = require("../model/db");
//添加商品种类
router.post("/", async (req, res) => {
    const data = await db.Goods.create(req.body);
    res.send({
        code: 0,
        message: "",
        data
    });
})
//查询单个商品
router.get("/:id", async (req, res) => {
    const data = await db.Goods.findById(req.params.id);
    res.send({
        code: 0,
        message: "",
        data
    });
})
//查询所有商品

router.get("/", async (req, res) => {
    if (!req.query.field) {
        req.query.field = "_id";
    }
    if (!req.query.sort) {
        req.query.sort = "asc";
    }
    let s = req.query.field;
    if (req.query.sort === "desc") {
        s = "-" + s;
    }
    //分页
    if (!req.query.page) {
        req.query.page = 1;
    }
    if (!req.query.limit) {
        req.query.limit = 4;
    }
    const page = parseInt(req.query.page);
    const limit = parseInt(req.query.limit);
    let condition={};
    if(req.query.key){
        const exp=new RegExp(req.query.key,"i");
        condition={
            $or:[
                {taste:{$regex:exp}},
            ]        
        };
    }
    const data = await db.Goods.find(condition).sort(s).skip((page - 1) * limit).limit(limit);
    const count = await db.Goods.countDocuments(condition);
    res.send({
        code: 0,
        message: "",
        data
    });
})
//修改商品
router.put("/:id",async (req,res)=>{
    const data = await db.Goods.updateOne({
        _id:req.params.id
    },req.body)
    res.send({
        code: 0,
        message: "",
        data
    });
})
//删除商品
router.delete("/:id",async(req,res)=>{
    const data = await db.Goods.deleteOne({
        _id: db.ObjectId(req.params.id)
    });
    res.send({
        code: 0,
        message: "",
        data
    });
})
module.exports = router;
